package com.lxr0860.lxr0860production_test;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.GridView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;


import com.lxr0860.lxr0860production_test.adapter.FactoryTestIemAdapter;
import com.lxr0860.lxr0860production_test.bean.FactoryTestItem;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.FileUtils;
import com.lxr0860.lxr0860production_test.utils.ThreadPool;
import com.lxr0860.lxr0860production_test.utils.ToastUtils;

import org.jetbrains.annotations.Nullable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by uniriho on 2018/8/15.
 */

public class MainActivity extends Activity implements FactoryTestIemAdapter.OnGridButtonClickListener {

    private GridView mGvMainItem;
    private List<FactoryTestItem> testItems;
    private FactoryTestIemAdapter mAdapter;
    private File logDir;
    private boolean destroy;
    private int mCurrentPosition;

    private static final int MAIN_REQUSTCODE = 100;
    private static final int UPDATE_UI = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_UI:
                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    };
    private TextView titleTv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mGvMainItem = (GridView) findViewById(R.id.gv_main_item);
        titleTv = findViewById(R.id.title);
    }

    private void initData() {
        testItems = new ArrayList<FactoryTestItem>();
        mAdapter = new FactoryTestIemAdapter(this, testItems);
        mGvMainItem.setAdapter(mAdapter);
        verifyStoragePermissions(this);

        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                MainLog();
            }
        });
    }

    private void initEvent() {
        mAdapter.setOnGridButtonClickListener(this);
//        titleTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(MainActivity.this, AIDLTest.class));
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MAIN_REQUSTCODE) {
            if (data != null && data.getBooleanExtra("result", false)) {
                if (mCurrentPosition == Contants.TEST_JILU) {
                    Log.e("cly", "重置测试记录");
                    for (int i = 0; i < testItems.size(); i++) {
                        testItems.get(i).setCanTest(true);
                    }
                } else {
                    testItems.get(mCurrentPosition).setCanTest(false);
                    if (mCurrentPosition == Contants.TEST_LAOHUA) {
                        FileUtils.writeFile(Contants.LOG_FACTORY_PATH
                                + File.separator + "" + Contants.TEST_LAOHUA + ".txt", "true");
                    }
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void startNextActivity(int position) {
        Intent intent = null;
        mCurrentPosition = position;
        if (position == Contants.TEST_JILU) {
            intent = new Intent(MainActivity.this, TestRecordActivity.class);
        } else if (position == Contants.TEST_LAOHUA) {
            intent = new Intent(MainActivity.this, LaoHuaActivity.class);
        } else if (position == Contants.TEST_QIANGHUA) {
            intent = new Intent(MainActivity.this, StrengthActivity.class);
        } else if (position == Contants.TEST_CHECK) {
            intent = new Intent(MainActivity.this, CheckInfoActivity.class);
        } else if (position == Contants.TEST_CODEBINDING) {
            intent = new Intent(MainActivity.this, UpdateRecordeActivity.class);
        }/*else if (position == Contants.TEST_SETNUMBER) {
            intent = new Intent(MainActivity.this, SetNumberActivity.class);
        } */else {
            intent = new Intent(MainActivity.this, TestItemActivity.class);
            intent.putExtra("testType", position);
        }
        if (intent != null) {
            startActivityForResult(intent, MAIN_REQUSTCODE);
        }
    }

    private void MainLog() {
        if (logDir == null) {
            logDir = new File(Contants.LOG_FACTORY_PATH);
            if (logDir.exists() && logDir.isFile()) {
                logDir.delete();
            }
            if (!logDir.exists() || !logDir.isDirectory()) {
                logDir.mkdir();
            }
        }
        for (int i = 0; i <= Contants.TEST_CODEBINDING; i++) {
            FactoryTestItem item = new FactoryTestItem(Contants.getTopTitle(i),
                    true, R.drawable.main_test_btn_bg, i);
            testItems.add(item);
        }
        if (logDir.exists() && logDir.isDirectory()) {
            BufferedReader bufr = null;
            try {
                File[] files = logDir.listFiles();
                for (File file : files) {
                    if (destroy) {
                        return;
                    }
                    bufr = new BufferedReader(new FileReader(file));
                    String line;
                    boolean testComplete = false;
                    while ((line = bufr.readLine()) != null) {
                        if (destroy) {
                            bufr.close();
                            return;
                        }
                        if (line.equals("true")) {
                            testComplete = true;
                            break;
                        }
                    }
                    bufr.close();
                    bufr = null;
                    testItems.get(Integer.parseInt(file.getName().substring(0, 1)))
                            .setCanTest(!testComplete);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufr != null) {
                    try {
                        bufr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        handler.sendEmptyMessage(UPDATE_UI);
    }

    private static final int PERMISSION_CHECK = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO};

    /**
     * Checks if the app has permission to write to device storage
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int tfcard = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int location = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.ACCESS_COARSE_LOCATION);
        int fine_location = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.ACCESS_COARSE_LOCATION);
        int phone = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.READ_PHONE_STATE);
        int camera = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.CAMERA);
        int recoder = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);

        if (tfcard != PackageManager.PERMISSION_GRANTED ||
                location != PackageManager.PERMISSION_GRANTED ||
                fine_location != PackageManager.PERMISSION_GRANTED ||
                phone != PackageManager.PERMISSION_GRANTED ||
                camera != PackageManager.PERMISSION_GRANTED ||
                recoder != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    PERMISSION_CHECK);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CHECK) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    ToastUtils.showMessage("获取权限失败");
                    finish();
                }
            }
        }
    }

    private int enterCount = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.e("dispatchKeyCode", event.getKeyCode() + "");

        return super.dispatchKeyEvent(event);
    }
}
